<template>
  <div class="role-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">角色管理</h1>
          <p class="page-subtitle">管理系统角色及其权限配置</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" size="large" @click="handleAddRole">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <el-card class="table-card">
        <el-table
          :data="roleList"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#475569',
            fontWeight: '600',
            fontSize: '14px'
          }"
          :row-style="{ height: '60px' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="name" label="角色名称">
            <template #default="{ row }">
              <div class="role-name">
                <el-icon class="role-icon"><Avatar /></el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-info">
                <el-icon class="time-icon"><Clock /></el-icon>
                <span>{{ row.created_at }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" plain @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button size="small" type="danger" plain @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="600px"
      class="role-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        label-position="top"
        class="role-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序">
              <el-input-number v-model="roleForm.sort" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="角色权限" prop="permissions">
          <div class="permission-tree">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionTreeData"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              default-expand-all
              class="custom-tree"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '创建角色' : '保存修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Avatar, Clock, Edit, Delete } from '@element-plus/icons-vue'

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 角色列表
const roleList = ref<any[]>([])
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const roleFormRef = ref()
const permissionTreeRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 角色表单
const roleForm = reactive({
  id: undefined,
  name: '',
  description: '',
  sort: 0,
  permissions: []
})

// 权限树数据
const permissionTreeData = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      { id: 11, label: '用户管理' },
      { id: 12, label: '角色管理' },
      { id: 13, label: '权限管理' }
    ]
  },
  {
    id: 2,
    label: '内容管理',
    children: [
      { id: 21, label: '文章管理' },
      { id: 22, label: '分类管理' },
      { id: 23, label: '标签管理' }
    ]
  },
  {
    id: 3,
    label: '系统设置',
    children: [
      { id: 31, label: '基础设置' },
      { id: 32, label: '日志管理' }
    ]
  }
])

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    // 这里应该是实际的 API 调用
    // const response = await getRoles({
    //   page: pagination.current,
    //   page_size: pagination.pageSize
    // })
    // roleList.value = response.results
    // pagination.total = response.count
    
    // 模拟数据
    roleList.value = [
      {
        id: 1,
        name: '超级管理员',
        description: '拥有系统所有权限',
        created_at: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '普通管理员',
        description: '拥有部分管理权限',
        created_at: '2024-01-15 09:15:00'
      },
      {
        id: 3,
        name: '普通用户',
        description: '基础权限用户',
        created_at: '2024-01-14 16:20:00'
      }
    ]
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 新增角色
const handleAddRole = () => {
  dialogType.value = 'add'
  roleForm.id = undefined
  roleForm.name = ''
  roleForm.description = ''
  roleForm.sort = 0
  roleForm.permissions = []
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  roleForm.id = row.id
  roleForm.name = row.name
  roleForm.description = row.description
  roleForm.sort = row.sort || 0
  // 这里应该获取角色的权限
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '提示',
      { type: 'warning' }
    )
    
    // 这里应该是实际的 API 调用
    // await deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchRoles()
  } catch (error) {
    console.log('取消删除')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    
    submitLoading.value = true
    
    // 获取选中的权限
    const checkedPermissions = permissionTreeRef.value.getCheckedKeys()
    roleForm.permissions = checkedPermissions
    
    if (dialogType.value === 'add') {
      // 这里应该是实际的 API 调用
      // await createRole(roleForm)
      ElMessage.success('角色创建成功')
    } else {
      // 这里应该是实际的 API 调用
      // await updateRole(roleForm.id, roleForm)
      ElMessage.success('角色更新成功')
    }
    
    dialogVisible.value = false
    fetchRoles()
  } catch (error) {
    console.log('表单验证失败')
  } finally {
    submitLoading.value = false
  }
}

// 分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchRoles()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchRoles()
}

onMounted(() => {
  fetchRoles()
})
</script>

<style scoped lang="scss">
.role-management {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);

  // 页面头部
  .page-header {
    margin-bottom: 32px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      padding: 0;

      .title-section {
        .page-title {
          font-size: 28px;
          font-weight: 700;
          color: #1e293b;
          margin: 0 0 8px 0;
          letter-spacing: -0.025em;
        }

        .page-subtitle {
          font-size: 14px;
          color: #64748b;
          margin: 0;
        }
      }

      .header-actions {
        .el-button {
          font-weight: 500;
          border-radius: 8px;
          padding: 12px 24px;
          
          .el-icon {
            margin-right: 6px;
          }
        }
      }
    }
  }

  // 主要内容区域
  .content-section {
    .table-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 0;
      }

      // 表格样式
      .el-table {
        :deep(.el-table__header-wrapper) {
          .el-table__header {
            th {
              border-bottom: 2px solid #e2e8f0;
              
              .cell {
                padding: 16px 12px;
              }
            }
          }
        }

        :deep(.el-table__body-wrapper) {
          .el-table__body {
            tr {
              &:hover {
                background: #f8fafc;
              }

              td {
                border-bottom: 1px solid #f1f5f9;
                
                .cell {
                  padding: 16px 12px;
                }
              }
            }
          }
        }

        // 角色名称样式
        .role-name {
          display: flex;
          align-items: center;
          gap: 8px;

          .role-icon {
            font-size: 16px;
            color: #3b82f6;
          }

          span {
            font-weight: 500;
            color: #1e293b;
          }
        }

        // 时间信息样式
        .time-info {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #64748b;
          font-size: 13px;

          .time-icon {
            font-size: 14px;
          }
        }

        // 操作按钮样式
        .action-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;

          .el-button {
            border-radius: 6px;
            font-weight: 500;
            padding: 6px 12px;
            
            .el-icon {
              margin-right: 4px;
            }

            &.el-button--primary {
              &.is-plain {
                &:hover {
                  background: #3b82f6;
                  border-color: #3b82f6;
                  color: white;
                }
              }
            }

            &.el-button--danger {
              &.is-plain {
                &:hover {
                  background: #ef4444;
                  border-color: #ef4444;
                  color: white;
                }
              }
            }
          }
        }
      }

      // 分页样式
      .pagination-wrapper {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background: #fafbfc;
        display: flex;
        justify-content: flex-end;

        :deep(.el-pagination) {
          .el-pager {
            li {
              border-radius: 6px;
              margin: 0 2px;
              font-weight: 500;

              &.is-active {
                background: #3b82f6;
                color: white;
              }
            }
          }

          .btn-prev,
          .btn-next {
            border-radius: 6px;
            margin: 0 2px;
          }
        }
      }
    }
  }

  // 对话框样式
  :deep(.role-dialog) {
    .el-dialog__header {
      padding: 24px 24px 0;
      
      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 0 24px 24px;
    }
  }

  // 表单样式
  .role-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
      }

      .el-input,
      .el-textarea {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:hover {
            border-color: #9ca3af;
          }

          &.is-focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }
        }
      }

      .el-input-number {
        width: 100%;
        
        :deep(.el-input__wrapper) {
          border-radius: 8px;
        }
      }
    }

    // 权限树样式
    .permission-tree {
      border: 1px solid #d1d5db;
      border-radius: 8px;
      padding: 16px;
      background: #f9fafb;
      max-height: 300px;
      overflow-y: auto;

      .custom-tree {
        background: transparent;
        
        :deep(.el-tree-node) {
          .el-tree-node__content {
            padding: 8px 0;
            border-radius: 6px;
            margin: 2px 0;
            transition: background 0.3s ease;

            &:hover {
              background: rgba(59, 130, 246, 0.05);
            }

            .el-tree-node__label {
              font-size: 14px;
              color: #374151;
              font-weight: 500;
            }

            .el-checkbox {
              margin-right: 8px;
            }
          }

          .el-tree-node__children {
            .el-tree-node__content {
              padding-left: 24px;
              
              .el-tree-node__label {
                color: #6b7280;
                font-weight: 400;
              }
            }
          }
        }
      }
    }
  }

  // 对话框底部
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 10px 24px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .role-management {
    padding: 16px;

    .page-header {
      .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;

        .title-section {
          .page-title {
            font-size: 24px;
          }
        }

        .header-actions {
          .el-button {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }

    .content-section {
      .table-card {
        .el-table {
          // 移动端表格样式调整
          .action-buttons {
            flex-direction: column;
            gap: 4px;

            .el-button {
              font-size: 12px;
              padding: 4px 8px;
            }
          }
        }

        .pagination-wrapper {
          padding: 16px;
          
          :deep(.el-pagination) {
            .el-pagination__total,
            .el-pagination__sizes,
            .el-pagination__jump {
              display: none;
            }
          }
        }
      }
    }

    .role-form {
      .el-row {
        .el-col {
          &:not(:last-child) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>